package com.example.mptnet;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.News;
import com.example.mptnet.Models.RP;
import com.example.mptnet.Models.User;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainFragment extends Fragment {
    SharedPreferences settings;
    SharedPreferences.Editor edit;
    RelativeLayout layout, news;
    API api;
    Retrofit retrofit;
    ArrayList<RP> rp = new ArrayList<RP>();
    String UID = "";
    User user = new User();
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        settings = getContext().getApplicationContext().getSharedPreferences("SETTINGS", MODE_PRIVATE);
        edit = settings.edit();
        layout = view.findViewById(R.id.layout);
        news = view.findViewById(R.id.news);
        TextView text = new TextView(getContext());
        text.setTextSize(14);
        text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        retrofit = Builder.request();
        api = retrofit.create(API.class);
        UID = settings.getString("UID", "");
        Call<User> calluser = api.GetUser(UID);
        calluser.enqueue(new Callback<User>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    user = response.body();
                    if (!user.getUsers_group().equals("default")) {
                        edit.putString("group", user.getUsers_group());
                        edit.commit();
                        DayOfWeek day = LocalDate.now().getDayOfWeek();
                        Call<ArrayList<RP>> callRP = api.GetRP(user.getUsers_group());
                        callRP.enqueue(new Callback<ArrayList<RP>>() {
                            @Override
                            public void onResponse(Call<ArrayList<RP>> call, Response<ArrayList<RP>> response) {
                                if (response.isSuccessful()) {
                                    rp = response.body();
                                    for (RP item : rp)
                                        if (item.weekday.equals(day.getDisplayName(TextStyle.FULL, new Locale("ru")).toUpperCase(Locale.ROOT)))
                                            text.setText(item.get_rp());
                                    if (text.getText().equals("")) text.setText("Выходной");
                                }
                            }

                            @Override
                            public void onFailure(Call<ArrayList<RP>> call, Throwable t) {
                                Log.e("Ошибка", t.getMessage());
                            }
                        });
                        layout.addView(text);
                    }
                    else{
                        Toast.makeText(getContext(),"Группа не была найдена в вашем профиле!", Toast.LENGTH_LONG).show();
                    }
                }

            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Log.e("Ошибка", t.getMessage());
                Toast.makeText(getContext(),"Нет соединения с интернетом", Toast.LENGTH_LONG).show();
            }
        });
        Call<ArrayList<News>> callnews = api.getNews();
        callnews.enqueue(new Callback<ArrayList<News>>() {
            @Override
            public void onResponse(Call<ArrayList<News>> call, Response<ArrayList<News>> response) {
                if(response.isSuccessful()){
                    TextView textView = new TextView(getContext());
                    for (int i = 0; i < response.body().size(); i++) {
                        textView.append(response.body().get(i).getDescription() + "\n"+response.body().get(i).getDate()+"\n\n");
                    }
                    news.addView(textView);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<News>> call, Throwable t) {

            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Вызываем обработку нажатия кнопки "назад"
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                // Обработка нажатия кнопки "назад"
                onBackPressed();
                return true;
            }
            return false;
        });
    }

    private void onBackPressed() {
        if (getActivity() != null) {
            System.exit(0);
        }
    }
}